/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servidorped;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import servidorped.NetworkManager1.NetworkReader;
import servidorped.NetworkManager1.NetworkSender;

/**
 *
 * @author Micosil
 */
public class Conexion implements Runnable {

    User user;
    NetworkReader reader;
    NetworkSender sender;    
    CommandProcessor cmp = new CommandProcessor();

    public Conexion(Socket accept) {
        user = new User(accept, null, null, null, null, "false");
        reader = user.getUserListener();
        sender = user.getUserSender();

    }

    @Override
    public void run() {

        
        sender.setToSend("Conexión establecida. Por favor, identifíquese usando el comando /login o cree una cuenta de usuario con /register \n");
        while (user.isConnected) {
            try {
                if ((!user.getUserSocket().isClosed()) && sender.thereIsStuffToSend()) {
                    sender.sendAll();
                }
            } catch (Exception ex) {
                user.closeConnection();
                break;
            }
            try {
                while ((!user.getUserSocket().isClosed()) && reader.thereAreThingsToRead()) {
                    cmp.process(reader.readln().trim(), user);
                }
            } catch (Exception ex) {
                user.closeConnection();
                break;
            }                       
        }
    }
}
